package com.ruiysoft.controller.mdse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruiysoft.controller.mdse.vo.Category;
import com.ruiysoft.entity.mdse.MerchandiseCategory;
import com.ruiysoft.entity.mdse.MerchandiseSpu;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.pub.consts.EnumUtil;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.mdse.IMerchandiseCategoryService;
import com.ruiysoft.service.mdse.IMerchandiseSpuService;
import com.ruiysoft.service.mdse.consts.MdseEnum;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-10-27T01:43:53.483+08:00")

@RestController
public class CategoryApiController implements CategoryApi {

    private static final Logger log = LoggerFactory.getLogger(CategoryApiController.class);

    private final IMerchandiseCategoryService categoryService;

    private final IMerchandiseSpuService spuService;

    @org.springframework.beans.factory.annotation.Autowired
    public CategoryApiController(IMerchandiseCategoryService categoryService,IMerchandiseSpuService spuService) {
        this.categoryService = categoryService;
        this.spuService = spuService;
    }
    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }

//    @Cacheable(value = "categoryListGet")
    @Override
    public Result<PageInfo<Category>> categoryListGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, @ApiParam(value = "分类名") @Valid @RequestParam(value = "name", required = false) String name) {
        Long shopId = getShopId();
        try{
            IPage<MerchandiseCategory> page = categoryService.page(new Page<>(pageStart,pageSize),new QueryWrapper<MerchandiseCategory>().eq("shop_id",shopId).eq("del_flag",EnumUtil.DelFlag.NO.getIndex()));
            List<Category> list = new ArrayList<>();
            page.getRecords().forEach(cate ->{
                list.add(new Category().id(cate.getCategoryId())
                        .name(cate.getCategoryName())
                        .photo(cate.getIcon())
                        .delFlag(cate.getDelFlag()));
            });
            return ResultGenerator.genSuccessResult(new PageInfo<Category>(list, (Page) page));
        } catch (Exception e) {
            log.error("商铺查询分类--{}--{}--{}--{}",shopId,pageStart,pageSize,name, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

//    @CacheEvict(value="categoryListGet", allEntries=true)
    @Override
    public Result<Void> categorySavePost(@ApiParam(value = ""  )  @Valid @RequestBody Category body) {
        Long shopId = getShopId();
        try {
            if(body.getId()!=null){
                MerchandiseCategory cate = categoryService.getById(body.getId());
                if(cate!=null&&!Objects.equals(cate.getShopId(),shopId)){
                    throw new Exception("登录店铺不是此分类所属店铺");
                }
            }
            categoryService.saveOrUpdate(new MerchandiseCategory()
                    .setCategoryId(body.getId())
                    .setCategoryName(body.getName())
                    .setShopId(shopId)
                    .setIcon(body.getPhoto())
                    .setDelFlag(body.getDel_flag())
                );
            return ResultGenerator.genSuccessResult();

        } catch (Exception e) {
            log.error("商铺保存分类--{}--{}",shopId,JSONObject.toJSONString(body), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @CacheEvict(value = "categoryListGet")
    @Override
    public Result<Void> categoryDelIdPost(@ApiParam(value = "删除的分类id",required=true) @PathVariable("id") Long id) {
        Long shopId = getShopId();
        try {
            MerchandiseCategory cate = categoryService.getById(id);
            if(cate==null){
                throw new Exception("无此分类");
            }
            if(!Objects.equals(cate.getShopId(),shopId)){
                throw new Exception("登录店铺不是此分类所属店铺");
            }
            int cout = spuService.count(new QueryWrapper<MerchandiseSpu>().eq("status",MdseEnum.MdseStatus.UP.getIndex()).eq("main_category",id));
            if(cout>0){
                throw new Exception("此分类下还有上架的商品");
            }
            categoryService.updateById(new MerchandiseCategory()
                    .setCategoryId(id)
                    .setDelFlag(EnumUtil.DelFlag.YES.getIndex())
            );
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("商铺删除分类--{}--{}",shopId,id, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<PageInfo<Category>> list4Pc(@ApiParam(value = "分页开始页", required = true) @RequestParam(value = "pageStart", required = true) @NotNull @Valid Integer pageStart, @ApiParam(value = "每页显示多少条数据", required = true) @RequestParam(value = "pageSize", required = true) @NotNull @Valid Integer pageSize, @ApiParam(value = "分类名") @RequestParam(value = "name", required = false) @Valid String name) {
        Long shopId = getShopId();
        try{
            IPage<MerchandiseCategory> page = categoryService.page(new Page<>(pageStart,pageSize),new QueryWrapper<MerchandiseCategory>().eq("shop_id",shopId).eq("del_flag", 0));
            List<Category> list = new ArrayList<>();
            page.getRecords().forEach(cate ->{
                list.add(new Category().id(cate.getCategoryId())
                        .name(cate.getCategoryName())
                        .photo(cate.getIcon())
                        .delFlag(cate.getDelFlag()));
            });

            return ResultGenerator.genSuccessResult(new PageInfo<Category>(list, (Page) page));

        } catch (Exception e) {
            log.error("商铺查询分类--{}--{}--{}--{}",shopId,pageStart,pageSize,name, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }
}
